#!/bin/bash
#----------------- procedures ----------------
printDebug ()
{
  local LEVEL=$1
  local MESSAGE="$2"
  if [ "$LEVEL" = "0" ]; then
    echo "  `date +%H:%M:%S`: $MESSAGE"
  elif [ "$SIM_DEBUGGING" = "yes" ]; then
    echo "    Debug `date +%H:%M:%S`: $MESSAGE"
#   if [ "$SERVER_NAME" != "" ]; then
#     echo "<BR>"
#   fi
  fi
}

printLongIp ()
{
IP=$1
COUNT=1
for NUM in `echo "$IP" | awk -F. '{ print $1 " " $2 " " $3 " " $4 }'`
do
  if [ "${#NUM}" -eq "1" ]; then
    printf 00$NUM
  elif [ "${#NUM}" -eq "2" ]; then
    printf 0$NUM
  else
    printf $NUM
  fi
  if [ "$COUNT" -lt "4" ]; then
    printf "."
  fi
  COUNT=`expr $COUNT + 1`
done
}

testIpAddr ()
{
  local IPADDR=$1
  for NUM in `echo $IPADDR | sed 's/\./ /g'`
  do
    if [ "$NUM" -ge "0" ] && [ "$NUM" -le "255" ]; then
      printf "x"
    else
      printf "nok"
    fi
  done
}

testNodeTypeColor ()
{
local NODETYPE=$1
  case $NODETYPE in
      (${NETNAME[1]})  TYPECOLOR=${NETBG[1]} ;;
      (${NETNAME[2]})  TYPECOLOR=${NETBG[2]} ;;
      (${NETNAME[3]})  TYPECOLOR=${NETBG[3]} ;;
      (${NETNAME[4]})  TYPECOLOR=${NETBG[4]} ;;
      (${NETNAME[5]})  TYPECOLOR=${NETBG[5]} ;;
      (${NETNAME[6]})  TYPECOLOR=${NETBG[6]} ;;
      (${NETNAME[7]})  TYPECOLOR=${NETBG[7]} ;;
      (${NETNAME[8]})  TYPECOLOR=${NETBG[8]} ;;
      (${NETNAME[9]})  TYPECOLOR=${NETBG[9]} ;;
      (${NETNAME[10]})  TYPECOLOR=${NETBG[10]} ;;
      (${NETNAME[11]})  TYPECOLOR=${NETBG[11]} ;;
      (${NETNAME[12]})  TYPECOLOR=${NETBG[12]} ;;
      (${NETNAME[13]})  TYPECOLOR=${NETBG[13]} ;;
      (${NETNAME[14]})  TYPECOLOR=${NETBG[14]} ;;
      (${NETNAME[15]})  TYPECOLOR=${NETBG[15]} ;;
      (*)              TYPECOLOR=${NETBG[0]} ;;
  esac
  printf "$TYPECOLOR"
}

displaySubnetList ()
{
  SUBNETDIR=$SIM_SUBNETD
    echo "<CENTER>
          <H3>Subnetinfo</H3>"
  if [ -d $SUBNETDIR ]; then
    echo "<TABLE BORDER=2>
        <TR BGCOLOR=#DDDDDD>
        <TD>NAME<BR>SUBNET MASK BROADCAST</TD>
        <TD>FIXED</TD>
        <TD>DHCP dynamic / options</TD>
        </TR>"
    ls $SUBNETDIR | sort | while read FILE
    do
#     echo "<TR><TD COLSPAN=5>$FILE</TD></TR>"
      cat $SUBNETDIR/$FILE | while read TYPE REST
      do
#       echo "<TR><TD COLSPAN=5>($TYPE $REST)</TD></TR>"
        case $TYPE in
        (NAME:)           NAME=$REST ;;
        (NETWORK:)        NETWORK=`echo $REST | awk '{ print $1 }'` 
                          MASK=`echo $REST | awk '{ print $2 }'`
                          BROADCAST=`echo $REST | awk '{ print $3 }'`
                          ;;
        (RANGE:)          NODETYPE=`echo $REST | awk '{ print $1 }'`
                          NODECOLOR=`testNodeTypeColor $NODETYPE`
                          if [ "`echo $REST | awk '{ print $5 }'`" = "default" ]; then
                            BGCOLOR=#BBBBBB
                          else
                            BGCOLOR=$NODECOLOR
                          fi
                          NET="$NET `echo $REST | awk '{ print "<TR><TD BGCOLOR='$NODECOLOR'>" $1 "</TD><TD BGCOLOR='$BGCOLOR'>" $2 "</TD><TD BGCOLOR='$BGCOLOR'>" $3 "</TD><TD BGCOLOR='$BGCOLOR'>" $4 "</TD></TR>"}' `" ;;
        (DHCP:)           DHCP="$DHCP $REST<BR>" ;;
        (OPTION:)         OPTION="$OPTION option: $REST<BR>" ;;
        (---end---)             echo "<TR><TD VALIGN=TOP><A HREF=$SCRIPT_NAME?subnet+upd-subnet-info+$FILE>$NAME</A>
                                  <BR>
                                  $NETWORK
                                  $MASK
                                  $BROADCAST</TD>
                                  <TD VALIGN=TOP>
                                     <TABLE>$NET</TABLE>
                                  </TD>
                                  <TD VALIGN=TOP>$DHCP$OPTION</TD></TR>" 
                           ;;
#       (*)                echo "<TR><TD COLSPAN=5>Entry not recognized: ($TYPE $REST)</TD></TR>" ;;
        esac
      done
    done
    echo "</TABLE>"
  else
    echo "Subnet directory $SUBNETDIR not found!!!!!!"
  fi

}
removeRange ()
{
  NETFILE=$1
  RANGENAME=$2
  TMPFILE1=$SIM_TMPDIR/updsubnet-$NETWORK.$$
  echo "Removing range $RANGENAME from $NETFILE."
  grep -v "RANGE: $RANGENAME " $SIM_SUBNETD/$NETWORK > $TMPFILE1
  mv $TMPFILE1 $SIM_SUBNETD/$NETWORK
  NETWORK=`grep NETWORK: $SIM_SUBNETD/$NETWORK | awk '{ print $2 }'`
  $SIM_SUDO $SIM_LOGGERT $NETWORK "info RemRange, removed range $RANGENAME from $NETFILE by $REMOTE_USER"
}
updSubnetInfo ()
{
  # Display the update info form for an single subnet.
  FILE=$1
  echo "<FORM   method=post Action=$SCRIPT_NAME?subnet+run-upd-subnet-info+$FILE>
        <H2>Modify subnetdata for $FILE</H2>
        <A HREF=$SCRIPT_NAME?subnet+remove-subnet+$FILE>Remove subnet</A>
        <TABLE>"
  cat $SIM_SUBNETD/$FILE | while read TYPE REST
  do
    case $TYPE in
      (NAME:)           NAME=$REST ;;
      (NETWORK:)        NETWORK=`echo $REST | awk '{ print $1 }'`
                        MASK=`echo $REST | awk '{ print $2 }'`
                        BROADCAST=`echo $REST | awk '{ print $3 }'`
                        ;;
      (OPTION:)         OPTIONTYPE=`echo $REST | awk '{ print $1 }'`
                        OPTIONVALUE=`echo $REST | awk '{ print $2 }'`
                        case $OPTIONTYPE in 
                          (routers)  GATEWAY=$OPTIONVALUE ;;
                        esac
                        ;;
      (RANGE:)          NET="$NET
                             <TR>
                               <TD>`echo $REST | awk '{ print $1 "</TD><TD>" $2 "</TD><TD>" $3 "</TD><TD>" $4 }'`</TD>
                               <TD><A HREF=$SCRIPT_NAME?subnet+modify-range+$FILE+${REST[0]}>(mod)</A>
                                 <A HREF=$SCRIPT_NAME?subnet+remove-range+$FILE+${REST[0]}>(rem)</A>
                               </TD>
                             </TR>" ;;
      (DHCP:)           DHCP="$DHCP $REST" ;;
      (---end---)
        echo "<INPUT TYPE=hidden NAME=network VALUE='$NETWORK'>
              <TR><TD>Info</TD><TD COLSPAN=2>Network: $NETWORK, Mask: $MASK, Broadcast: $BROADCAST.</TD></TR>
              <TR><TD>Name:</TD>
              <TD>$NAME</TD><TD><INPUT NAME=newname Size=90 Type=text VALUE='$NAME'>
                                        <INPUT TYPE=hidden NAME=oldname VALUE='$NAME'></TD></TR>
              <TR><TD VALIGN=top>Ranges</TD>
              <TD COLSPAN=2><TABLE>$NET</TABLE></TD></TR>
              <TR><TD>Gateway</TD>
              <TD>$GATEWAY</TD><TD><INPUT NAME=newgateway Size=90 Type=text VALUE='$GATEWAY'>
                                        <INPUT TYPE=hidden NAME=oldgateway VALUE='$GATEWAY'></TD></TR>"
    esac
  done
  echo "</TABLE>
        <INPUT TYPE=submit Value=UPDATE>
        </FORM>"

}

runUpdSubnetInfo ()
{
  NETFILE=$1
  TMPFILE1=$SIM_TMPDIR/updsubnet-$NETWORK.$$
  echo "Checking changed info. ($SUBNETDIR/$NETWORK)"
  if [ "$FORM_newname" != "$FORM_oldname" ]; then
    echo "Name has changed, updating namereccord for addresrange."
    grep -v NAME: $SIM_SUBNETD/$NETWORK | grep -v -e "---end---" > $TMPFILE1
    echo "NAME: $FORM_newname" >> $TMPFILE1
    echo "---end---" >> $TMPFILE1
    mv $TMPFILE1 $SIM_SUBNETD/$NETWORK
    $SIM_SUDO $SIM_LOGGERT $FORM_network "info Netname updated by $REMOTE_USER to $FORM_newname ($FORM_oldname)"
  fi
  if [ "$FORM_newgateway" != "$FORM_oldgateway" ]; then
    echo "Gateway changed"
    grep -v "OPTION: routers" $SIM_SUBNETD/$NETWORK | grep -v -e "---end---" > $TMPFILE1
    echo "OPTION: routers $FORM_newgateway" >> $TMPFILE1
    echo "---end---" >> $TMPFILE1
    mv $TMPFILE1 $SIM_SUBNETD/$NETWORK
    $SIM_SUDO $SIM_LOGGERT $FORM_network "info Gateway updated by $REMOTE_USER to $FORM_newgateway ($FORM_oldgateway)"
  fi

}

modifyRange ()
{
  FILE=$1
  RANGE=$2
  echo "<FORM   method=post Action=$SCRIPT_NAME?subnet+run-modify-range+$FILE+$RANGE>
        <H2>Modify data for range $RANGE in $FILE</H2>
        <TABLE>"
  RECCORD=( `grep "RANGE: $RANGE " $SIM_SUBNETD/$FILE` )
  echo "<INPUT TYPE=hidden NAME=network VALUE='$NETWORK'>
        <TR><TD>Name</TD><TD><INPUT NAME=name SIZE=15 TYPE=text VALUE=${RECCORD[1]}></TD></TR>
        <TR><TD>Start</TD><TD><INPUT NAME=start SIZE=15 TYPE=text VALUE=${RECCORD[2]}></TD></TR>
        <TR><TD>End</TD><TD><INPUT NAME=end SIZE=15 TYPE=text VALUE=${RECCORD[3]}></TD></TR>
        <TR><TD>Dns prefix</TD><TD><INPUT NAME=dnsprefix SIZE=15 TYPE=text VALUE=${RECCORD[4]}></TD></TR>
        <INPUT TYPE=hidden NAME=default VALUE='${RECCORD[5]}'>
        </TABLE>
        <INPUT TYPE=submit Value=UPDATE>
        </FORM>"
}

runModifyRange ()
{
  FILE=$1
  RANGE=$2
  if [ -f $SIM_TMPDIR/$FILE ]; then
    rm $SIM_TMPDIR/$FILE
  fi
  cat $SIM_SUBNETD/$FILE | while read TYPE NAME START END PREFIX DEFAULT
  do
    if [ "$TYPE" = "" ]; then
      SKIP=yes
    elif [ "$TYPE $NAME" = "RANGE: $RANGE" ]; then
      echo "RANGE: $FORM_name $FORM_start $FORM_end $FORM_dnsprefix $FORM_default" >> $SIM_TMPDIR/$FILE
    else
      echo "$TYPE $NAME $START $END $PREFIX $DEFAULT" >> $SIM_TMPDIR/$FILE
    fi
  done
  mv $SIM_TMPDIR/$FILE $SIM_SUBNETD/$FILE
  echo "Update range info<PRE>"
  cat $SIM_SUBNETD/$FILE
  echo "<PRE>"
}
addSubnet ()
{
  echo "Adding subnet."
  echo "<FORM method=post Action=$SCRIPT_NAME?subnet+addnet>
        <TABLE>
        <TR><TD>Subnet address:</TD><TD><INPUT NAME=subnet Size=16 Type=text></TD></TR>
        <TD>Subnet template</TD>
        <TD><select name=template size=1>
                  <option value=none>- select -</option>"
  ls $SIM_SUBNETTEMPL | while read FILE
  do
    echo "<option value=$FILE>$FILE</option>"
  done
  echo "</SELECT></TD></TR>      
        </TABLE>
        <INPUT TYPE=submit Value=Add>
        </FORM>"
}

calcNewIp ()
{
  IP1=( `echo $1 | sed 's/\./ /g'` )
  IP2=( `echo $2 | sed 's/\./ /g'` )
  for NUM in 0 1 2 3
  do
    if [ "$NUM" != "0" ]; then
      printf "."
    fi
    NEWIP[$NUM]=`expr ${IP1[$NUM]} + ${IP2[$NUM]}`
    printf ${NEWIP[$NUM]}
  done
}

runAddSubnet ()
{
  echo "Running add subnet action for $FORM_subnet<BR>"
  ABORT=none
  if [ "`testIpAddr $FORM_subnet`" = "xxxx" ]; then
    echo "Ipaddr=oke<BR>"
  else
    ABORT="ipaddr seems wrong"
  fi
  if [ "$FORM_template" != "none" ]; then
    echo "Using template $FORM_template<BR>"
  else
    ABORT="mask invalid"
  fi
  
  if [ -r "$LONGFILE" ]; then
    ABORT="subnet already exists <BR>"
  fi
  if [ "$ABORT" = "none" ]; then
    echo "Setting the folowing info<BR>"
    NETMASK=`grep "NETWORK:" $SIM_SUBNETTEMPL/$FORM_template | awk '{ print $3 }'`
    IPIN=( `echo $FORM_subnet | sed 's/\./ /g'` )
    MASKIN=( `echo $NETMASK | sed 's/\./ /g'` )
    for NUM in 0 1 2 3
    do
      if [ "${MASKIN[$NUM]}" = "255" ]; then
        if [ "$NEWSUBNET" = "" ]; then
          NEWSUBNET=${IPIN[$NUM]}
        else
          NEWSUBNET=$NEWSUBNET.${IPIN[$NUM]}
        fi
      else
        NEWSUBNET=$NEWSUBNET.0
      fi  
    done
    LONGFILE=$SIM_SUBNETD/net-`printLongIp $NEWSUBNET`
    if [ -r "$LONGFILE" ]; then
      echo "subnet already exists ($LONGFILE)<BR>"
    else
      echo "Creating subnet info for $NEWSUBNET/$NETMASK.<BR>"
      TMPFILE=$SIM_TMPDIR/net-`printLongIp $NEWSUBNET`.$$
      touch $LONGFILE
      if [ -w "$LONGFILE" ]; then
        cat $SIM_SUBNETTEMPL/$FORM_template | while read LINE
        do
          printDebug 1 "$LINE"
          for ITEM in $LINE
          do
            # calculate the ipaddr based on the subnet mask for all ip's but the mask.
            if [ "`testIpAddr $ITEM`" = "xxxx" ] && [ "`echo $ITEM | awk -F. '{ print $1 }'`" != "255" ]; then
              NEWIPNUM=`calcNewIp $NEWSUBNET $ITEM`
              if [ "${#ITEM}" = "15" ]; then
                NEWIPNUM=`printLongIp $NEWIPNUM`
              fi
              printf "$NEWIPNUM " >> $LONGFILE
            else
              printf "$ITEM " >> $LONGFILE
            fi
          done
          printf "\n" >> $LONGFILE
        done
        echo "---end---" >> $LONGFILE

        echo "created the subnetfile net-`printLongIp $NEWSUBNET`.<BR>"
        cat "$LONGFILE"
      else
        printDebug 0 "The file $LONGFILE is not writeable."
      fi
    fi
  else
    echo "Subnet not added, reason $ABORT."
  fi
  
}

runRemoveSubnet ()
{

  SUBNET=$1
  FILE=$SIM_SUBNETD/$SUBNET
  if [ -f $FILE ]; then
    rm $FILE
  else
    echo "Oops, subnetfile $FILE not found."
  fi
}
# ------------------------------- Main -------------------------------- 
ACTION=$1
NETWORK=$2
PARAM1=$3
if [ "$ACTION" = "none" ]; then
  ACTION=displist
fi
if [ "$NETWORK" = "" ]; then
  NETWORK=none
fi

echo " 
<A HREF=$SCRIPT_NAME?subnet+add>Add</A> 
</TD></TR></TABLE>"

if [ "$ACTION" = "displist" ]; then
  displaySubnetList
elif [ "$USERLEVEL" -gt "5" ]; then
  if [ "$ACTION" = "upd-subnet-info" ]; then
    updSubnetInfo $NETWORK
  elif [ "$ACTION" = "run-upd-subnet-info" ]; then
    runUpdSubnetInfo $NETWORK
  elif [ "$ACTION" = "add" ]; then
    # Display the form to add the subnet.
    addSubnet
  elif [ "$ACTION" = "addnet" ]; then
    # Add the subnet
    runAddSubnet
  elif [ "$ACTION" = "remove-subnet" ]; then
    runRemoveSubnet $NETWORK
  elif [ "$ACTION" = "modify-range" ]; then
    modifyRange $NETWORK $PARAM1
  elif [ "$ACTION" = "run-modify-range" ]; then
    runModifyRange $NETWORK $PARAM1
  elif [ "$ACTION" = "remove-range" ]; then
    removeRange $NETWORK $PARAM1
  else
    echo "Oops, sorry subnet action $ACTION not coded."
  fi
else
  echo "Sorry , you are not authorised to use this action."
fi
# ---------- end ----------
